<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018/5/24
 * Time: 10:28
 */

namespace app\api\controller;


use app\base\controller\ApiBaseController;
use think\Exception;
use think\facade\Config;
use think\facade\Request;
use think\Image;

/**
 * Class Image
 * @package app\api\controller
 *
 */

/**
 * 返回样例
 * {
        error_code: 0,
        msg: "文件处理成功",
        data: [
            {
            file: {
                source: "static/uploads/default/20180604/d567e74d87c93255bca27679ff8fda50.exe"
            },
            fileSource: "static/uploads/default/20180604/d567e74d87c93255bca27679ff8fda50.exe"
            },
            {
            file: {
                source: "static/uploads/image/20180604/c60d26a24bef5c1e5d2190c71a2ef86c.png",
                200x200: "static/uploads/image/20180604/c60d26a24bef5c1e5d2190c71a2ef86c@200x200png",
                400x400: "static/uploads/image/20180604/c60d26a24bef5c1e5d2190c71a2ef86c@400x400png",
                750x750: "static/uploads/image/20180604/c60d26a24bef5c1e5d2190c71a2ef86c@750x750png",
                1500x1500: "static/uploads/image/20180604/c60d26a24bef5c1e5d2190c71a2ef86c@1500x1500png"
            },
            fileSource: "public/uploads/image/20180604/c60d26a24bef5c1e5d2190c71a2ef86c.png"
            }
        ],
        url: "",
        source: ""
    }
 *
 *
 */
class FileUpload extends ApiBaseController
{

    //允许上传的文件后缀
    protected $ext = [];

    //文件上传大小 （B字节为单位）
    protected $size = 0;

    //文件验证规则
    protected $fileValidate = [];

    //图片上传，默认生成缩略图
    protected $createThumbImg = true;

    //获取上传文件总数
    protected $fileInfo = '';

    //文件路径
    public $fileDirect = [
        'default' => '../public/static/uploads/default/', //默认文件存放路径
        'image' =>'../public/static/uploads/image/', // 产品图片
        'video'  =>'../public/static/uploads/video/', //产品文件
    ];

    public $_thumb_size = ['400'];

    /**
     * 文件上传处理
     * User: Jason
     */
    public function upload2()
    {
        //文件处理初始化
        $this->initUploadFile();
        //获取上传文件数据
        $file = Request()->file();
        $this->fileInfo  = reset($file);
        $dealRes = $this->move();
        wapAjaxReturn(0,'文件处理成功',$dealRes);
    }

    public function upload(){
        try{
            //接收上传的文件
            $file = $this->request->file('file');
            $useOrigin = Request::param('useOrigin');

            $savename = $useOrigin == 1?true:false;

            //图片存的路径
            $imgUrl= $this->fileDirect['default'] .  date("Y/m/d");
            if(!empty($file)){

                // 移动到框架应用根目录/public/uploads/ 目录下

                $info = $file->validate(['size'=>2*1024*2014,'ext'=>'jpg,png,gif,jpeg'])->rule('uniqid')->move($imgUrl,$savename);
                $error = $file->getError();
                $originName = $file->getInfo('name');
                //验证文件后缀后大小
                if(!empty($error)){
                    throw new Exception($file->getError());
                }
                if($info){
                    // 成功上传后 获取上传信息
                    //获取图片的名字
                    $imgName = $info->getFilename();
                    //获取图片的路径
                    $photo=$imgUrl . "/" . $imgName;

                }else{
                    // 上传失败获取错误信息
                    throw new Exception($file->getError());
                }
            }else{
                $photo = '';
            }
            if($photo !== ''){
                $thumbImg = $this->newCreateThumbImg($photo);
                $photo = str_replace("../public",'',$photo);
                return ['code'=>1,'msg'=>'成功','photo'=>$photo,'origin_name'=>$originName,'thumb'=>$thumbImg];
            }else{
                return ['code'=>404,'msg'=>'失败'];
            }
        }catch (Exception $exception){
            return ['code'=>404,'msg'=>$exception->getMessage()];
        }

    }



    protected function newCreateThumbImg($originImg){
        $newImg = [];
        $fileNameStr = explode(".",$originImg);
        $imageExt = end($fileNameStr); unset($fileNameStr[count($fileNameStr)-1]);
        foreach ($this->_thumb_size as $v){
            $image = \think\Image::open($originImg);
            // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png

            $newImgName = implode(".",$fileNameStr) . '@' . $v . '.' . $imageExt;

            $image->thumb($v, $v)->save($newImgName);
            $newImg[] = $newImgName;
        }

        if('gif' === $imageExt){
            //gif 直接复制原图
            foreach ($this->_thumb_size as $v){
                $newImgName = implode(".",$fileNameStr) . '@' . $v . '.' . $imageExt;
                copy($originImg,$newImgName);
                $newImg[] = $newImgName;
            }
        }else{
            //对原图进行比例裁剪
            foreach ($this->_thumb_size as $v){
                $image = \think\Image::open($originImg);
                // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png

                $newImgName = implode(".",$fileNameStr) . '@' . $v . '.' . $imageExt;

                $image->thumb($v, $v)->save($newImgName);
                $newImg[] = $newImgName;
            }
        }

        return $newImg;

    }










    /**
     * 文件上传
     * User: Jason
     * @param $files
     */
    protected function move(){
        $fileData = [];
        //获取上传文件总数
        foreach ($this->fileInfo as $k=>$file){
            wapAjaxReturn(0,'文件处理成功',$file);
            try{
                $fileTypeInfo = $file->getInfo()['type'];
                $fileType = explode('/',$fileTypeInfo)[0]; // 获取文件类型
                $movePath = isset($this->fileDirect[$fileType]) ? $this->fileDirect[$fileType] : $this->fileDirect['default']; //获取文件存储位置
                if (!is_dir($movePath)) {  //判断是否创建了存放上传图片的文件夹
                    mkdir($movePath, 0777, true);
                }
                $info = $file->validate($this->fileValidate)->move($movePath);

                if($info){
                    $fileData[$k]['file']['source'] = str_replace("../public/",'',$movePath.$info->getSaveName());
                    $fileData[$k]['fileSource'] = str_replace("../public/",'',$movePath.$info->getSaveName());
                }else{
                    //获取异常,终止当前文件后续的操作
                    $fileData[$k]['fileError'] = $info->getError();
                    continue;
                }
                if('image' === $fileType and true === $this->createThumbImg){
                    //生成缩略图
                    $fileData[$k]['file'] = array_merge($fileData[$k]['file'],$this->getThumbImg($info->getSaveName(),$fileType,$movePath));
                }
            }catch (Exception $e){
                $fileData[$k]['fileError'] = $e->getMessage();
                continue;
            }
        }
        return $fileData;
    }


    /**
     * 裁剪图片
     * User: Jason
     * @param $fileName  文件生成路径
     * @param $fileType  文件类型
     * @param $movePath  文件保存路径
     * @return array
     */
    protected function getThumbImg($fileName,$fileType,$movePath){
        if('image' !== $fileType){return  [];}
        //获取缩略图比例
        $imageSize = Config('params.uploadDefaultSize');
        //返回缩略图数组
        $returnFile = [];
        //将原图文件名拆分
        $fileNameStr = explode(".",$fileName);
        $imageExt = end($fileNameStr); unset($fileNameStr[count($fileNameStr)-1]);
        if('gif' === $fileType){
            //gif 直接复制原图
            foreach (explode(",", $imageSize) as $k => $v) {
                $thumbImagePath = $movePath . implode(".",$fileNameStr) . '@' . $v . $imageExt;
                copy($movePath.$fileName,$thumbImagePath);
                $returnFile[$v] = str_replace("../public/",'',$thumbImagePath);
            }
        }else{
            //对原图进行比例裁剪
            foreach (explode(",", $imageSize) as $k => $v) {
                $thumbSize = explode("x", $v);
                $image = Image::open($movePath.$fileName);
                $thumbImagePath = $movePath . implode(".",$fileNameStr) . '@' . $v . '.' . $imageExt;
                $image->crop($thumbSize[0], $thumbSize[1])->save($thumbImagePath);
                $returnFile[$v] = str_replace("../public/",'',$thumbImagePath);
            }
        }
        return $returnFile;
    }

    /**
     * 文件上传初始化
     * User: Jason
     */
    protected function initUploadFile()
    {
        //判断是否有文件上传
        $this->checkFile();
        //获取请求数据中的变量，设置文件上传基础参数
        $fileSize = Request::param('fileSize','default'); //文件大小
        $fileType = Request::param('fileType','default');//文件类型
        $this->getFileSize($fileSize);
        $this->getExt($fileType);
    }

    /**
     * 初始化数据校验
     * User: Jason
     * @throws \HttpRequestException
     */
    protected function checkFile(){
        if(!Request()->file()){
            if(Request::isAjax()){
                wapAjaxReturn(400,'请选择上传的文件');
            }else{
                throw new \Exception('请选择上传的文件');
            }
        }
    }

    /**
     * 处理文件大小
     * User: Jason
     * @param $fileSize
     */
    protected function getFileSize($fileSize){
        if(isset(Config::get('params.fileSize')[$fileSize])){
            $this->size = Config::get('params.fileSize')[$fileSize];
        }else{
            $this->size = Config::get('params.fileSize')['default'];
        }
        $this->fileValidate['size'] = $this->size;
    }

    /**
     * 处理文件类型
     * User: Jason
     * @param $fileExt
     */
    protected function getExt($fileType){
        if(isset(Config::get('params.fileExt')[$fileType])){
            $this->ext = Config::get('params.fileExt')[$fileType];
            $this->fileValidate['ext'] = $this->ext;
        }
    }
}